<template>
    <view class="container">
        <NavBar :isShowIcon="false" :isCentered="true" title="计量" :add="text" @redirect="goToAddMaterial" />
        <view class="filter-area">
            <view class="filter-item" @click="toggleFilter('project')">
                <text class="filter-text" :class="{'filter-text-color':selectedFilters.project.projectName}">{{ selectedFilters.project.projectName }}</text>
                <!-- <image :src="activeFilter === 'project' ? '/static/arrow-up.png' : '/static/arrow-down.png'"
                    class="arrow-icon"></image> -->
					<uv-icon name="arrow-down-fill" :color="selectedFilters.project.projectName?'#3c9cff':''"></uv-icon>
            </view>
            <view class="filter-item" @click="toggleFilter('contract')">
                <text class="filter-text" :class="{'filter-text-color':selectedFilters.contract.contractName}">{{ selectedFilters.contract.contractName }}</text>
                <!-- <image :src="activeFilter === 'contract' ? '/static/arrow-up.png' : '/static/arrow-down.png'"
                    class="arrow-icon"></image> -->
					<uv-icon name="arrow-down-fill" :color="selectedFilters.contract.contractName?'#3c9cff':''"></uv-icon>
            </view>
            <view class="filter-item" @click="toggleFilter('cycle')" v-show="cycleData.length">
                <text class="filter-text" :class="{'filter-text-color':selectedFilters.cycle.cycleName}">{{ selectedFilters.cycle.cycleName }}</text>
                <!-- <image :src="activeFilter === 'cycle' ? '/static/arrow-up.png' : '/static/arrow-down.png'"
                    class="arrow-icon"></image> -->
					<uv-icon name="arrow-down-fill" :color="selectedFilters.cycle.cycleName?'#3c9cff':''"></uv-icon>
            </view>
        </view>
        <view class="metering-section" @click="openTreePicker">
            <text class="metering-text">清单</text>
            <text class="metering-path">{{ selectedNodePath }}</text>
            <image src="/static/arrow-right.png" class="metering-arrow"></image>
        </view>
        <scroll-view refresher-enabled="true" @refresherrefresh="refresherrefresh" :refresher-triggered='refresh' class="material-list" scroll-y >
            <!-- 表格 -->
            <!-- <view class="table-container">
                <view class="table">
                    <view class="table-header">
                        <view class="table-cell"><text>编号</text></view>
                        <view class="table-cell"><text>名称</text></view>
                        <view class="table-cell"><text>计量</text></view>
                        <view class="table-cell"><text>总金额</text></view>
                        <view class="table-cell"><text>上限量</text></view>
                        <view class="table-cell"><text>期末量</text></view>
                    </view>
                    <view class="table-row" v-for="(item, index) in tableData" :key="index">
                        <view class="table-cell"><text>{{ item.costNumber }}</text></view>
                        <view class="table-cell"><text>{{ item.costName }}</text></view>
                        <view class="table-cell"><text>{{ item.projectNum }}</text></view>
                        <view class="table-cell"><text>{{ (Number(item.unitPrice || 0) * Number(item.projectNum || 0))
                        }}</text></view>
                        <view class="table-cell"><text>{{ item.upperlimitNum }}</text></view>
                        <view class="table-cell"><text>{{ item.totalProjectNum }}</text></view>
                    </view>
                </view>
            </view> -->
			<uv-empty mode="data" text="暂无数据" v-if="tableData.length==0 && isempty" ></uv-empty>
			<view class="list-item" v-for="(item, index) in tableData" :key="index">
				<view class="item-box">
					<view class="title">
						子目编号
					</view>
					<view class="content">
						{{ item.costNumber }}
					</view>
				</view>
				<view class="item-box">
					<view class="title">
						子目名称
					</view>
					<view class="content">
						{{ item.costName }}
					</view>
				</view>
				<view class="item-box">
					<view class="title">
						本期计量
					</view>
					<view class="content">
						{{ item.projectNum }}
					</view>
				</view>
				<view class="item-box">
					<view class="title">
						劳务金额
					</view>
					<view class="content">
						{{ (Number(item.unitPrice || 0) * Number(item.projectNum || 0))}}
					</view>
				</view>
				<view class="item-box">
					<view class="title">
						上限量
					</view>
					<view class="content">
						{{ item.upperlimitNum }}
					</view>
				</view>
				<view class="item-box">
					<view class="title">
						本期末量
					</view>
					<view class="content">
						{{ item.totalProjectNum }}
					</view>
				</view>
			</view>
        </scroll-view>
        <!-- 动态筛选下拉菜单 -->
        <view class="dropdown-container" @click="closeFilter" v-if="activeFilter" >
        	<scroll-view  class="list" scroll-y>
        	    <view class="dropdown-mask" @click="closeFilter"></view>
        	    <view class="dropdown-content">
        	        <template v-if="activeFilter === 'project'">
        	            <view class="dropdown-item" v-for="item in projectData" :key="item.id"
        	                @click="selectFilter('project', item)">
        	                <text class="textStyle" :class="{ selected: selectedFilters.project.id === item.id }">{{
        	                    item.projectName }}</text>
        	            </view>
        	        </template>
        	        <template v-if="activeFilter === 'contract'">
        	            <view class="dropdown-item" v-for="item in contractData" :key="item.id"
        	                @click="selectFilter('contract', item)">
        	                <text :class="{ selected: selectedFilters.contract.id === item.id }">{{ item.contractName
        	                    }}</text>
        	            </view>
        	        </template>
        	        <template v-if="activeFilter === 'cycle'">
        	            <view class="dropdown-item" v-for="item in cycleData" :key="item.is"
        	                @click="selectFilter('cycle', item)">
        	                <text :class="{ selected: selectedFilters.cycle.id === item.id }">{{ item.cycleName }}</text>
        	            </view>
        	        </template>
        	    </view>
        	</scroll-view>
        </view>
        <view v-if="showTreePicker" class="popup-container">
            <view class="popup-mask" @click="closeTreePicker"></view>
            <view class="tree-popup-content">
                <view class="selected-path">
                    <text>当前选择: {{ selectedNodePath }}</text>
                </view>
                <scroll-view scroll-y class="tree-scroll-view">
					<view class="check-all" @click="checkAll">
						全选
					</view>
                    <template v-for="node1 in treeData" :key="node1.id">
                        <view class="tree-node level-1" :class="{ selected: selectedNodeId === node1.id }"
                            @click="toggleNode(node1, treeData)">
                            <view class="node-arrow" v-show="node1.children && node1.children.length"
                                :class="{ open: node1.open }"></view>
                            <text class="node-text">{{ node1.label }}</text>
                        </view>
                        <view v-if="node1.open" class="node-children">
                            <template v-for="node2 in node1.children" :key="node2.id">
                                <view class="tree-node level-2" :class="{ selected: selectedNodeId === node2.id }"
                                    @click="toggleNode(node2, node1.children)">
                                    <view class="node-arrow" v-show="node2.children && node2.children.length"
                                        :class="{ open: node2.open }"></view>
                                    <text class="node-text">{{ node2.label }}</text>
                                </view>
                                <view v-if="node2.open" class="node-children">
                                    <template v-for="node3 in node2.children" :key="node3.id">
                                        <view class="tree-node level-3"
                                            :class="{ selected: selectedNodeId === node3.id }"
                                            @click="toggleNode(node3, [node1, node2])">
                                            <text class="node-text">{{ node3.label }}</text>
                                        </view>
                                    </template>
                                </view>
                            </template>
                        </view>
                    </template>
                </scroll-view>
            </view>
        </view>
    </view>
    <!-- 浮动添加按钮 -->
    <view v-if="showAddButton" class="add-button-container" @click="goToAddMaterial">
        <view class="add-button">
            <image src="/static/cl_add.png" mode="aspectFill" class="add-image"></image>
        </view>
    </view>
</template>

<script>
import NavBar from '@/components/NavBar/index.vue'
import {
    getProjectList,
    getContractList,
    getCyclemanagementList,
    getTreeselectList,
    getMeteringpayList,
	getTotalNumber
} from '@/utils/app.js'
export default {
    components: {
        NavBar
    },
    data() {
        return {
			isempty:false,
			refresh:false,
            activeFilter: null,
            selectedFilters: {
                project: {
                    id: '',
                    name: ''
                },
                contract: {
                    id: '',
                    name: ''
                },
                cycle: {
                    id: '',
                    name: ''
                },
            },
            selectedNodePath: '',
            tableData: [],
            projectData: [],
            showTreePicker: false,
            selectedNodeId: '',
            showAddButton: false,
            treeData: [],
            queryParams: {},
            selectedNode: {},
			text:'',
			cycleData:[],
			parentId:''
        };
    },
    watch: {
        'selectedFilters.contract.id'(newId, oldId) {
            if (newId) {
                this.queryParams.contractId = newId;
                this.getCyclemanagementData(this.queryParams);
            }
        },
		parentId(newId, oldId){
			if(newId==0){
				this.text = ''
			}else{
				this.text = '新增'
			}
		}
    },
	onShow() {
		if(JSON.stringify(this.selectedNode) != '{}'){
			this.getMeteringpayData(this.queryParams);
			this.getTreeselectData(this.queryParams);
			getTotalNumber(this.queryParams).then(res=>{
				console.log(res);
				this.selectedNode.addNum = res.data
			})
		}
		this.queryParams = {}
		this.selectedNodeId = ''
		this.selectedNodePath = ''
		this.getProjectData();
		
	},
    onLoad(option) {
		console.log(option);
        // this.getProjectData();
		
    },
	onHide() {
		console.log(111111);
		this.showTreePicker = false
		this.queryParams = {}
		this.selectedFilters = {}
		this.activeFilter = null
		this.tableData = []
	},
	async onPullDownRefresh() {
		
	    await this.getMeteringpayData(this.queryParams);
	    uni.stopPullDownRefresh()
	},
    methods: {
        // onPullDownRefresh() {
        //     this.getProjectData()
        // },
		async refresherrefresh(){
			this.refresh = true
			await this.getMeteringpayData(this.queryParams);
			this.refresh = false
		},
        //获取计量
        getTreeselectData(data) {
            getTreeselectList(data).then(res => {
                if (res.code == 200) {
                    this.treeData = res.data;
                }
            })
        },
        //获取项目列表
        getProjectData() {
            getProjectList().then(res => {
                if (res.code = 200) {
                    this.projectData = res.rows;
                    this.selectedFilters.project = res.rows[0];
                    this.queryParams = {
                        projectId: res.rows[0].id,
                    }
                    this.getContractData(this.queryParams);
                }
            })
        },
        //获取合同列表
        getContractData(data) {
            getContractList(data).then(res => {
                if (res.code == 200) {
                    this.contractData = res.rows;
                    this.selectedFilters.contract = res.rows[0];
					this.parentId = res.rows[0].parentId
                    this.queryParams = {
                        projectId: this.queryParams.projectId,
                        contractId: res.rows[0].id
                    };
                    // this.getCyclemanagementData(this.queryParams);
                }
            })
        },
        //获取周期列表 
        getCyclemanagementData(data) {
            getCyclemanagementList(data).then(res => {
                if (res.code == 200) {
                    this.cycleData = res.rows;
                    this.selectedFilters.cycle = res.rows[0];
                    this.queryParams = {
                        projectId: this.queryParams.projectId,
                        contractId: this.queryParams.contractId,
                        cycleId: res.rows.length?res.rows[0].id:null
                    }
                    // 获取树形数据的同时也会获取表格数据
                    this.getTreeselectData(this.queryParams);

                    this.getMeteringpayData(this.queryParams)
                }
            })
        },
        //获取计量列表
        getMeteringpayData(data) {
			// 显示加载提示
			uni.showLoading({
				title: "加载中",
				mask: true
			});
            getMeteringpayList(data).then(res => {
				// 隐藏加载提示
				uni.hideLoading();
                if (res.code == 200) {
                    this.tableData = res.rows || [];
					if(this.tableData.length==0){
						this.isempty = true
					}else{
						this.isempty = false
					}

                    // 如果有数据，更新queryParams中的相关信息
                    if (this.tableData && this.tableData.length > 0) {
                        this.queryParams.costNumber = this.tableData[0].costNumber || '';
                        this.queryParams.costName = this.tableData[0].costName || '';
                        this.queryParams.level = this.tableData[0].level || '';
                        this.queryParams.unit = this.tableData[0].unit || '';
                        this.queryParams.upperlimitNum = this.tableData[0].upperlimitNum || '';
                        this.queryParams.unitPrice = this.tableData[0].unitPrice || '';
                    }
                } else {
                    this.tableData = [];
                }
            }).catch(() => {
                this.tableData = [];
            })
        },
        toggleFilter(filter) {
            this.selectedNodePath = '';
            if (this.activeFilter === filter) {
                this.activeFilter = null;
            } else {
                this.activeFilter = filter;
            }
			console.log(filter,this.activeFilter);
        },
        openTreePicker() {
            this.showTreePicker = true;
        },
        closeFilter() {
            this.activeFilter = null;
        },
        selectFilter(type, value) {
			console.log(value);
            this.selectedFilters[type] = value;
            if (type === 'project') {
                const selectedProject = this.projectData.find(item => item.projectName === value.name);
				this.queryParams.projectId = value.id;
				 this.getContractData({projectId:value.id});
            } else if (type === 'contract') {
                this.selectedFilters.contract = this.contractData.find(item => item.id === value.id)
				this.parentId = value.parentId
            } else if (type === 'cycle') {
                this.selectedFilters.cycle = this.cycleData.find(item => item.id === value.id)
                this.queryParams.cycleId = value.id;
                this.getTreeselectData(this.queryParams);
				this.getMeteringpayData(this.queryParams)
            }
            this.closeFilter();
        },
        closeTreePicker() {
            this.showTreePicker = false;
        },
        toggleNode(node, siblings) {
            this.selectedNode = node;
            // 手风琴效果：关闭同级节点
            siblings.forEach((sibling) => {
                if (sibling.id !== node.id) {
                    sibling.open = false;
                }
            });

            // 切换当前节点展开状态
            const wasOpen = node.open;
            node.open = !wasOpen;

            // 如果有子节点，不设置 selectedNodeId 和 selectedNodePath
            if (!node.children || node.children.length === 0) {
                this.selectNode(node);
            }
        },
        selectNode(node) {
            const pathNodes = this.getNodePath(this.treeData, node.id);
            if (!pathNodes) {
                return;
            }
            this.queryParams.addNum = node.addNum;
            // 更新路径和当前选中 ID
            this.selectedNodeId = node.id;
            this.selectedNodePath = pathNodes.map(n => n.name || n.label).join(' / ');

            // 控制按钮显示
            // this.showAddButton = !node.children || node.children.length === 0;
			if(!node.children || node.children.length === 0){
				this.text = '新增'
			}else{
				this.text = ''
			}


            this.queryParams.sourceId = this.selectedNodeId;
            this.queryParams.reviewState;
            this.queryParams.dataSource = 1;
            this.queryParams.jlType = 1;
            this.queryParams.nodeType = 1;
            this.getMeteringpayData(this.queryParams);

            // 关闭弹窗
            this.showTreePicker = false;
        },
        getNodePath(tree, nodeId) {
            for (let node of tree) {
                if (node.id === nodeId) {
                    return [node];
                }
                if (node.children && node.children.length > 0) {
                    const result = this.getNodePath(node.children, nodeId);
                    if (result) {
                        return [node, ...result];
                    }
                }
            }
            return null;
        },
        goToAddMaterial() {
			if(JSON.stringify(this.selectedNode)=='{}'){
				return uni.showToast({
				  title: '请选择一条清单进行计量!',
				  icon: 'none'
				});
			}
			getTotalNumber(this.queryParams).then(res=>{
				console.log(res);
				this.selectedNode.addNum = res.data?res.data:'0'
				let data = {
				    ...this.queryParams,
				    ...this.selectedNode,
				}
				uni.navigateTo({
				    url: `/pages/metering/add?data=${encodeURIComponent(JSON.stringify(data))}`
				});
				console.log(data);
			})
            
        },
        selectFirstNode(node) {
            // 如果当前节点有子节点，递归查找第一个叶子节点
            if (node.children && node.children.length > 0) {
                // 展开第一个子节点
                node.open = true;
                this.selectFirstNode(node.children[0]);
            } else {
                // 找到叶子节点，选择它
                this.selectNode(node);
            }
        },
		checkAll(){
			const data = {
                        projectId: this.queryParams.projectId,
                        contractId: this.queryParams.contractId,
                        cycleId: this.queryParams.cycleId
                    }
			this.queryParams = data
			this.getMeteringpayData(data)
			this.showTreePicker = false
			this.selectedNodePath = ''
			this.selectedNodeId = ''
			this.text  = ''
		}
    }
}
</script>

<style lang="scss" scoped>
	*{
		box-sizing: border-box;
	}
	::v-deep .filter-text{
		font-size: 30rpx !important;
	}
.add-img {
    position: fixed;
    right: 40rpx;
    bottom: 200rpx;
    width: 120rpx;
}

.container {
    display: flex;
    flex-direction: column;
    min-height: calc(100vh - 60px);
    background-color: #e6eaf3;
    background-color: #e6eaf3;
}

.filter-area {
    display: flex;
    height: 40px;
    flex-direction: row;
    background-color: #ffffff;
    border-bottom-width: 1px;
    border-bottom-color: #eeeeee;
}

.filter-item {
    display: flex;
    width: 120rpx;
    flex: 1;
    flex-direction: row;
    justify-content: center;
    align-items: center;
}

.filter-text {
    font-size: 16px;
    color: #333333;
    font-weight: 400;
    padding-left: 15px;
    // width: 100rpx;
    overflow: hidden;
    white-space: nowrap;
    text-overflow: ellipsis;
}
.filter-text-color{
	color: #3c9cff;
}

.arrow-icon {
    width: 7.35px;
    height: 4.82px;
    margin-left: 5px;
}

.material-list {
    flex: 1;
    min-height: 0;
    padding-bottom: 70px;
    max-height: calc(100vh - 390rpx);
    overflow-y: auto;
}

.material-list ::-webkit-scrollbar {
    display: none;
    width: 0 !important;
    height: 0 !important;
    -webkit-appearance: none;
    background: transparent;
    color: transparent;
}

.list-item{
	width: 700rpx;
	padding: 20rpx 40rpx;
	margin: 0 auto;
	margin-bottom: 20rpx;
	border-radius: 40rpx;
	background-color: #fff;
	.item-box{
		display: flex;
		font-size: 30rpx;
		
		.title{
			width: 120rpx;
			text-align: right;
			margin-right: 20rpx;
		}
		.content{
			width: 480rpx;
			overflow: hidden;
			 text-overflow: ellipsis;
			 white-space: nowrap;
		}
	}
}

.metering-arrow {
    width: 12px;
    height: 12px;
}

.metering-section {
    display: flex;
    flex-direction: row;
    align-items: center;
    background-color: #ffffff;
    padding: 12px 15px;
    margin: 10px 0;
    border-top: 1px solid #f0f0f0;
    border-bottom: 1px solid #f0f0f0;
}

.metering-text {
    font-size: 30rpx;
    color: #333;
}

.metering-path {
    flex: 1;
    text-align: right;
    font-size: 14px;
    color: #999;
    margin-right: 8px;
}

.dropdown-container {
    position: absolute;
    top: 18%;
    left: 0;
    right: 0;
    bottom: 0;
    z-index: 99;
	background-color: rgba(0, 0, 0, 0.3);
	.list{
		height: 600rpx;
	}
}

.dropdown-mask {
    width: 100%;
    height: 100%;
    
}

.dropdown-item {
    padding: 12px 15px;
    border-bottom: 1px solid #f0f0f0;

    .textStyle {
        max-width: 500rpx;
        overflow: hidden;
        white-space: nowrap;
        text-overflow: ellipsis;
    }

    text {
        font-size: 14px;
        color: #333;
    }

    text.selected {
        color: #2b6bff;
        font-weight: bold;
    }
}

.dropdown-content {
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    background-color: #ffffff;
}

.popup-container {
    position: fixed;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    z-index: 100;
    display: flex;
    flex-direction: column;
    justify-content: flex-start;

}

.popup-mask {
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    background-color: rgba(0, 0, 0, 0.5);
    z-index: 101;
}

.tree-popup-content {
    position: relative;
    background-color: #fff;
    margin-top: 141px;
    max-height: 70vh;
    overflow: hidden;
    z-index: 102;
    display: flex;
    flex-direction: column;
}

.selected-path {
    padding: 10px;
    border-bottom: 1px solid #f0f0f0;
    color: #666;
    font-size: 14px;
}

.tree-scroll-view {
    flex: 1;
    min-height: 0;
    max-height: 40vh;
    overflow-y: auto;
	.check-all{
		margin-left: 30rpx;
		padding: 10rpx 0;
		font-size: 15px
	}
}

.tree-node {
    display: flex;
    flex-direction: row;
    align-items: center;
    padding: 10px 5px;
    font-size: 15px;
}

.node-arrow {
    width: 8px;
    height: 8px;
    margin-right: 8px;
    border-top: 2px solid #999;
    border-right: 2px solid #999;
    transform: rotate(45deg);
    transition: transform 0.2s ease-in-out;
}

.node-arrow.open {
    transform: rotate(135deg);
}

.level-3 .node-arrow {
    display: none;
}

.node-text {
    color: #333;
}

.tree-node.selected .node-text {
    color: #2b6bff;
    font-weight: bold;
}

.node-children {
    flex-direction: column;
}

.table-container {
    margin: 10px;

    .table {
        border: 1px solid #ebeef5;
        flex-direction: column;
        background-color: #fff;

        .table-header,
        .table-row {
            flex-direction: row;
            display: flex;
            justify-content: space-between;
        }

        .table-header {
            background-color: #fafafa;

            .table-cell text {
                font-weight: bold;
            }
        }

        .table-row:nth-child(2n) {
            background-color: #fafcff;
        }

        .table-cell {
            flex: 1;
            padding: 12px 5px;
            border-bottom: 1px solid #ebeef5;
            text-align: center;
            width: 60px;
            white-space: nowrap;
            overflow: hidden;
            text-overflow: ellipsis;

            &:not(:last-child) {
                border-right: 1px solid #ebeef5;
            }

            text {
                font-size: 14px;
                color: #606266;
                display: inline-block;
                max-width: 60px;
                overflow: hidden;
                text-overflow: ellipsis;
                white-space: nowrap;
            }
        }

        .table-row:last-child .table-cell {
            border-bottom: none;
        }
    }
}

.add-button-container {
    position: fixed;
    right: 15px;
    bottom: 87px;
    width: 60px;
    height: 60px;
    z-index: 100;
    background-color: transparent;
}

.add-button {
    width: 60px;
    height: 60px;
    position: relative;
}

.add-image {
    width: 60px;
    height: 60px;
    position: absolute;
    top: 0;
    left: 0;
}
</style>